<template>
  <div class="flex h-full flex-col">
    <!-- 搜索栏 -->

    <div class="flex justify-between">
      <el-form :inline="true" :model="queryParams" class="flex flex-wrap">
        <el-form-item label="组织名称" label-width="80px">
          <el-input
            v-model="queryParams.orgName"
            placeholder="请输入组织名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="状态" label-width="80px">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="Number(item.value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :icon="Search">查询</el-button>
          <el-button @click="handleReset" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
      <div>
        <el-button type="primary" @click="handleAdd" :icon="Plus">新增组织</el-button>
      </div>
    </div>

    <!-- 表格区域 -->
    <el-table
      class="h-0 grow"
      v-loading="loading"
      :data="organizationList"
      border
      stripe
      row-key="id"
      default-expand-all
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      style="width: 100%"
    >
      <el-table-column prop="orgName" label="组织名称" min-width="200" show-overflow-tooltip />
      <el-table-column prop="orgCode" label="组织编码" width="150" show-overflow-tooltip />
      <el-table-column prop="orgType" label="组织类型" width="120" align="center">
        <template #default="{ row }">
          <el-tag :type="getOrgTypeTagType(row.orgType)">
            {{ getOrgTypeLabel(row.orgType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="orgLevel" label="组织层级" width="100" align="center" />
      <el-table-column prop="contact" label="联系人" width="120" show-overflow-tooltip />
      <el-table-column prop="phone" label="联系电话" width="130" show-overflow-tooltip />
      <el-table-column prop="orderNum" label="排序" width="80" align="center" />
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" fixed="right" align="center">
        <template #default="{ row }">
          <el-button type="primary" link size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button type="success" link size="small" @click="handleAddChild(row)"
            >新增下级</el-button
          >
          <el-button type="danger" link size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="mt-2 flex justify-end">
      <el-pagination
        v-model:current-page="queryParams.page"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="700px" :destroy-on-close="true">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
        <el-form-item label="上级组织" prop="parentId">
          <el-tree-select
            v-model="formData.parentId"
            :data="organizationTreeOptions"
            :render-after-expand="false"
            check-strictly
            placeholder="请选择上级组织"
            node-key="id"
            :props="{ label: 'orgName', children: 'children' }"
            style="width: 100%"
          />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="组织名称" prop="orgName">
              <el-input v-model="formData.orgName" placeholder="请输入组织名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="组织编码" prop="orgCode">
              <el-input v-model="formData.orgCode" placeholder="请输入组织编码" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="组织类型" prop="orgType">
              <el-select
                v-model="formData.orgType"
                placeholder="请选择组织类型"
                style="width: 100%"
              >
                <el-option
                  v-for="item in orgTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="Number(item.value)"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="组织层级" prop="orgLevel">
              <el-input-number
                controls-position="right"
                v-model="formData.orgLevel"
                :min="1"
                :max="10"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系人" prop="contact">
              <el-input v-model="formData.contact" placeholder="请输入联系人" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="formData.phone" placeholder="请输入联系电话" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入邮箱" clearable />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="formData.address" placeholder="请输入地址" clearable />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="排序" prop="orderNum">
              <el-input-number
                controls-position="right"
                v-model="formData.orderNum"
                :min="0"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="formData.status">
                <el-radio
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="Number(item.value)"
                >
                  {{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="flex justify-end">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {
  createOrganization,
  deleteOrganization,
  getOrganizationById,
  getOrganizationList,
  getOrganizationTree,
  updateOrganization
} from '@/api/system/organization.api'
import { getDict, getDictOptions } from '@/utils/dict'
import { to } from '@/utils/promise'
import { Plus, Refresh, Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'

// 字典数据
const orgTypeOptions = ref<Array<{ label: string; value: string }>>([])
const statusOptions = ref<Array<{ label: string; value: string }>>([])
const orgTypeDictData = ref<DictData[]>([])

// 加载字典数据
const loadDictData = async () => {
  // 加载组织类型字典
  const [orgTypeError, orgTypeData] = await to(getDictOptions('org_type'))
  if (!orgTypeError && orgTypeData) {
    orgTypeOptions.value = orgTypeData
  }

  // 加载状态字典
  const [statusError, statusData] = await to(getDictOptions('org_status'))
  if (!statusError && statusData) {
    statusOptions.value = statusData
  }

  // 加载完整的组织类型字典数据（用于获取样式信息）
  const [dictError, dictData] = await to(getDict('org_type'))
  if (!dictError && dictData) {
    orgTypeDictData.value = dictData
  }
}

// 状态管理
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const currentEditId = ref<number>(0)

// 列表数据
const organizationList = ref<Organization[]>([])
const organizationTreeOptions = ref<Organization[]>([])
const total = ref(0)

// 查询参数
const queryParams = reactive<OrganizationQueryParams>({
  page: 1,
  pageSize: 10,
  orgName: '',
  status: undefined
})

// 表单数据
const formRef = ref<FormInstance>()
const formData = reactive<CreateOrganizationRequest>({
  parentId: 0,
  orgName: '',
  orgCode: '',
  orgType: 2,
  orgLevel: 1,
  managerId: undefined,
  contact: '',
  phone: '',
  email: '',
  address: '',
  remark: '',
  orderNum: 0,
  status: 1
})

// 表单验证规则
const formRules: FormRules = {
  parentId: [{ required: true, message: '请选择上级组织', trigger: 'change' }],
  orgName: [
    { required: true, message: '请输入组织名称', trigger: 'blur' },
    { max: 100, message: '组织名称不能超过100个字符', trigger: 'blur' }
  ],
  orgCode: [
    { required: true, message: '请输入组织编码', trigger: 'blur' },
    { max: 50, message: '组织编码不能超过50个字符', trigger: 'blur' }
  ],
  orgType: [{ required: true, message: '请选择组织类型', trigger: 'change' }],
  orgLevel: [{ required: true, message: '请输入组织层级', trigger: 'blur' }],
  phone: [
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }
  ],
  email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 获取组织类型标签
const getOrgTypeLabel = (type: number): string => {
  const item = orgTypeDictData.value.find((d) => d.dictValue === String(type))
  return item?.dictLabel || String(type)
}

// 获取组织类型标签类型（基于字典的 listClass）
const getOrgTypeTagType = (
  type: number
): 'primary' | 'success' | 'warning' | 'info' | 'danger' | undefined => {
  const item = orgTypeDictData.value.find((d) => d.dictValue === String(type))
  const listClass = item?.listClass || 'default'

  const typeMap: Record<string, 'primary' | 'success' | 'warning' | 'info' | 'danger' | undefined> =
    {
      primary: 'primary',
      success: 'success',
      warning: 'warning',
      info: 'info',
      danger: 'danger',
      default: undefined
    }

  return typeMap[listClass]
}

// 获取组织列表
const fetchOrganizationList = async () => {
  loading.value = true
  const [error, response] = await to(getOrganizationList(queryParams))
  if (error) {
    ElMessage.error('获取组织列表失败')
    return
  }
  // 将列表转换为树形结构
  organizationList.value = buildTree(response!.list || [], 0)
  total.value = response!.total || 0
  loading.value = false
}

// 获取组织树（用于选择上级组织）
const fetchOrganizationTree = async () => {
  const [error, response] = await to(getOrganizationTree())
  if (error) {
    ElMessage.error('获取组织树失败')
    return
  }
  organizationTreeOptions.value = [
    {
      id: 0,
      parentId: 0,
      orgName: '顶级组织',
      orgCode: 'root',
      orgType: 1,
      orgLevel: 0,
      status: 1
    },
    ...(response || [])
  ]
}

// 构建树形结构
const buildTree = (list: Organization[], parentId: number): Organization[] => {
  const tree: Organization[] = []
  for (const item of list) {
    if (item.parentId === parentId) {
      const children = buildTree(list, item.id)
      if (children.length > 0) {
        item.children = children
      }
      tree.push(item)
    }
  }
  return tree
}

// 搜索
const handleSearch = () => {
  queryParams.page = 1
  fetchOrganizationList()
}

// 每页条数改变
const handleSizeChange = (pageSize: number) => {
  queryParams.pageSize = pageSize
  queryParams.page = 1
  fetchOrganizationList()
}

// 页码改变
const handleCurrentChange = (page: number) => {
  queryParams.page = page
  fetchOrganizationList()
}

// 重置
const handleReset = () => {
  queryParams.page = 1
  queryParams.pageSize = 10
  queryParams.orgName = ''
  queryParams.status = undefined
  fetchOrganizationList()
}

// 新增
const handleAdd = () => {
  isEdit.value = false
  dialogTitle.value = '新增组织'
  resetForm()
  dialogVisible.value = true
}

// 新增下级
const handleAddChild = (row: Organization) => {
  isEdit.value = false
  dialogTitle.value = `新增下级组织（上级：${row.orgName}）`
  resetForm()
  formData.parentId = row.id
  formData.orgLevel = row.orgLevel + 1
  dialogVisible.value = true
}

// 编辑
const handleEdit = async (row: Organization) => {
  isEdit.value = true
  dialogTitle.value = '编辑组织'
  currentEditId.value = row.id

  const [error, response] = await to(getOrganizationById(row.id))
  if (error) {
    ElMessage.error('获取组织详情失败')
    return
  }
  Object.assign(formData, {
    parentId: response!.parentId || 0,
    orgName: response!.orgName,
    orgCode: response!.orgCode,
    orgType: response!.orgType,
    orgLevel: response!.orgLevel,
    managerId: response!.managerId,
    contact: response!.contact || '',
    phone: response!.phone || '',
    email: response!.email || '',
    address: response!.address || '',
    remark: response!.remark || '',
    orderNum: response!.orderNum || 0,
    status: response!.status
  })
  dialogVisible.value = true
}

// 删除
const handleDelete = (row: Organization) => {
  ElMessageBox.confirm(`确定要删除组织"${row.orgName}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const [error] = await to(deleteOrganization(row.id))
    if (error) {
      ElMessage.error('删除失败')
      return
    }
    ElMessage.success('删除成功')
    fetchOrganizationList()
    fetchOrganizationTree()
  })
}

// 取消
const handleCancel = () => {
  dialogVisible.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  formData.parentId = 0
  formData.orgName = ''
  formData.orgCode = ''
  formData.orgType = 2
  formData.orgLevel = 1
  formData.managerId = undefined
  formData.contact = ''
  formData.phone = ''
  formData.email = ''
  formData.address = ''
  formData.remark = ''
  formData.orderNum = 0
  formData.status = 1
  formRef.value?.resetFields()
}

// 提交
const handleSubmit = async () => {
  const [error] = await to<boolean, string>(formRef.value!.validate())
  if (error) {
    ElMessage.error(error || '表单验证失败')
    return
  }
  await formRef.value?.validate()
  submitLoading.value = true

  if (isEdit.value) {
    await updateOrganization(currentEditId.value, formData as any)
    ElMessage.success('更新成功')
  } else {
    await createOrganization(formData)
    ElMessage.success('创建成功')
  }

  dialogVisible.value = false
  fetchOrganizationList()
  fetchOrganizationTree()
  submitLoading.value = false
}

// 组件挂载时获取数据
onMounted(async () => {
  await loadDictData()
  fetchOrganizationList()
  fetchOrganizationTree()
})
</script>

<style scoped></style>
